const { Comment, Course, Attachment } = require("../../models");
const { Op } = require("sequelize");
const { paging } = require("../../utils/utils");
const { NotFoundError } = require("../../utils/errors");

/**
 * 获取评论列表
 * @param req
 * @returns {Promise<{count: number, pageSize: number, rows: Model[], currentPage: number}>}
 */
exports.list = async (req) => {
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    // 排序+分页
    const condition = {
      order: [["id", "ASC"]],
      limit: pageSize,
      offset: offset,
    };
    // 分页查询
    const { count, rows } = await Comment.findAndCountAll(condition);
    // 返回
    return { count, rows, currentPage, pageSize };
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 章节的评论列表
 * @param req
 * @returns {Promise<Model[]>}
 */
exports.all = async (req) => {
  try {
    // 排序
    const condition = {
      order: [["createdAt", "DESC"]],
      raw: true, //只返回数据的参数 --默认返回包装类
    };
    if (req.query.chapterId) {
      condition.where = {
        chapterId: {
          [Op.eq]: req.query.chapterId,
        },
      };
    }
    // 返回
    return await Comment.findAll(condition);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 创建评论
 * @param body
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
exports.create = async (body) => {
  try {
    return await Comment.create(body);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 删除评论
 * DELETE /Comments/:id
 */
exports.delete = async (id) => {
  try {
    const comment = await this.getById(id);
    await comment.destroy();
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 更新评论
 * @param id
 * @param body
 * @returns {Promise<Model<*, TModelAttributes>>}
 */
exports.update = async (id, body) => {
  try {
    const comment = await this.getById(id);
    return await comment.update(body); //删除
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 获取当前评论
 * @param id
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
exports.getById = async (id) => {
  // 获取当前评论
  const comment = await Comment.findByPk(id);
  if (!comment) {
    throw new NotFoundError(`ID: ${id} not found`);
  }
  return comment;
};
